﻿using AmuTools;
using app.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

/*
 * 全局类
 * 定时器和多线程在这里写
*/

namespace app.Api
{
	public class G
    {
        public static bool IsStarted = false;

        public static void StartApp()
        {
            if (IsStarted) return;
            Api.G.StartThread(); // 开启线程
            Api.G.StartTimer(); // 开启定时器
            TimerHelper.Run(); // 开启定时器辅助类
            IsStarted = true;
        }

        public static AmuTools.SqlHelper DB = new AmuTools.SqlHelper();

        // 创建一个缓存列表，缓存的数据放在里面
        public static Dictionary<string, object> CacheDic = new Dictionary<string, object>();

        public static Dictionary<string, Timer> TimerDic = new Dictionary<string, Timer>();

        #region 线程
        public static void StartThread()
        {
            Thread thread1 = new Thread(new ThreadStart(Thread1));
            thread1.Start();
        }
        private static void Thread1()
        {
        }
        #endregion

        #region 定时器
        public static void StartTimer()
        {
            // 更新首页信息，五分钟一次
            TimerDic["index"] = new Timer(ApiCommon.IndexTimer, null, 0, 5*60*1000);//1S定时器
            TimerHelper.Add(tu =>
            {
                // 自动执行统计工作,每天都统计一次。从2018年开始统计，statistic.current_date是统计进度，每次都会从这个时间开始统计
                DateTime date = DateTimeEx.TimeStampToDatetime(FreeValue.GetValue("statistic.current_date", "1514764800000"));
                while (date < DateTime.Now)
                {
                    date = date.AddDays(1);
                    Statistic.SaveOneDayData(date);
                    FreeValue.Set("statistic.current_date", DateTimeEx.DateTimeToTimeStamp(date));
                }
            }, 0, 86400000, -1);
        }
        #endregion

        public static List<string> CreateDatabase(Controller ctx, string storedprocedures_path)
        {
            return G.DB.CreateDataBase(new List<Type> {
                typeof(AdminRole), typeof(Admin), typeof(MemberRole), typeof(Member), typeof(Article),
                typeof(DemandItem), typeof(ServiceItem), typeof(UploadedFile), typeof(Abutment),
                typeof(Feedback),typeof(DataDictionary), typeof(Log), typeof(FreeValue),typeof(MemberMessage),
                typeof(HelpDocument),typeof(PlateformService),typeof(Template),typeof(Email),typeof(PlateformServiceAbutment),
                typeof(Step), typeof(StepData), typeof(StepAbutmentData), typeof(StepTemplate), typeof(ListedCompany),typeof(Phone),
                typeof(Statistic), typeof(GSXT)
            }, G.DB.GetSqlFiles(storedprocedures_path));
        }
    }
}